import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getList, checkoutAll } from '../store/actions/todos'
import TodoItem from './TodoItem'
const TodoList = () => {
  const dispatch = useDispatch()
  const { todos, filter } = useSelector((state) => state)
  useEffect(() => {
    dispatch(getList())
  }, [dispatch])
  const isChecked = todos.every((item) => item.done)
  let filterList
  if (filter === 'active') {
    filterList = todos.filter((item) => !item.done)
  } else if (filter === 'completed') {
    filterList = todos.filter((item) => item.done)
  } else {
    filterList = todos
  }
  return (
    <section className="main">
      <input
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
        checked={isChecked}
        onChange={(e) => dispatch(checkoutAll(e, todos))}
      />
      <label htmlFor="toggle-all">Mark all as complete</label>
      <ul className="todo-list">
        {filterList.map((item) => (
          <TodoItem key={item.id} item={item}></TodoItem>
        ))}
      </ul>
    </section>
  )
}

export default TodoList
